package services

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"strings"
)

const xmlUrl = "https://manuals.bmw-motorrad.com/manuals/WEBA/IN/BA-INTERNET-COM/01/Nav.xml"
const baiduUrl = "https://www.baidu.com"
const pdfBaseUrl = "https://manuals.bmw-motorrad.com/manuals/WEBA/IN/BA-INTERNET-COM/PDF/"

type Bmw struct {
}

type Navigation struct {
	XMLNAME xml.Name `xml:"NAVIGATION"`
	Mrs     []Navmr  `xml:"NAV-MR"`
}

type Navmr struct {
	XMLNAME xml.Name `xml:"NAV-MR"`
	MrName  string   `xml:"NAME"`
	Grps    []NavGrp `xml:"NAV-GRP"`
}

type NavGrp struct {
	XMLNAME xml.Name   `xml:"NAV-GRP"`
	GrpName string     `xml:"NAME"`
	Models  []NavModel `xml:"NAV-MODELL"`
}

type NavModel struct {
	XMLNAME   xml.Name  `xml:"NAV-MODELL"`
	Type      string    `xml:"TYPSCHL,attr"`
	ModelName string    `xml:"NAME"`
	Jahrs     []NavJahr `xml:"MODELLJAHR"`
}

type NavJahr struct {
	XMLNAME  xml.Name `xml:"MODELLJAHR"`
	JahrName string   `xml:"NAME"`
	Bas      []NavBa  `xml:"BA-SPRACHE"`
}

type NavBa struct {
	XMLNAME  xml.Name `xml:"BA-SPRACHE"`
	LangUage string   `xml:"LANGUAGE,attr"`
	FileName string   `xml:"FILENAME,attr"`
}

type CatalogRes struct {
	Model    string
	Year     string
	PartName string
	Url      string
}

func NewBmwRm() *Bmw {
	return &Bmw{}
}

func (b *Bmw) getXml() *Navigation {
	//response := util.NewHttpUtil().Get(xmlUrl)
	//body := response.Body()
	body, ioErr := ioutil.ReadFile("/Users/duanxu/Downloads/Nav.xml")
	if ioErr != nil {
		fmt.Println("xml file read error", ioErr)
		return nil
	}
	dom := &Navigation{}
	err := xml.Unmarshal(body, dom)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return dom
}

func (b *Bmw) GetPdfs() []*CatalogRes {
	res := make([]*CatalogRes, 0)
	dom := b.getXml()
	if dom == nil {
		fmt.Println("get xml or parser xml error")
		return res
	}
	for i := range dom.Mrs {
		navmr := dom.Mrs[i]
		for j := range navmr.Grps {
			//系列
			grp := navmr.Grps[j]
			for m := range grp.Models {
				//型号
				model := grp.Models[m]
				//型号名称
				name := model.ModelName
				for h := range model.Jahrs {
					jahr := model.Jahrs[h]
					//部件名称
					jahrName := jahr.JahrName
					for b := range jahr.Bas {
						ba := jahr.Bas[b]
						uage := ba.LangUage
						if uage == "01" {
							split := strings.Split(ba.FileName, "_")
							year := split[len(split)-1]
							pdfUrl := pdfBaseUrl + ba.FileName
							res = append(res, &CatalogRes{
								Model:    name,
								Year:     year,
								PartName: jahrName,
								Url:      pdfUrl,
							})
						}
					}
				}
			}
		}
	}
	return res
}
